package com.xiaohutech.tanmiao.utils;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.View;
import android.webkit.URLUtil;

import androidx.annotation.NonNull;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @创建者：yuan_xh
 * @创建时间： 2021/3/22 15:37
 * @描述：
 */
public class MatchUrlUtil {


    public static SpannableString getClickSpan(String content, String flag, int color, ClickUrlCallback callback) {
        if (TextUtils.isEmpty(content)) {
            content = "";
        }
        SpannableString spannableString = SpannableString.valueOf(content);
        return getClickSpan(spannableString, flag, color, callback);
    }

    public static SpannableString getClickSpan(CharSequence content, String flag, int color, ClickUrlCallback callback) {
        if (TextUtils.isEmpty(content)) {
            content = "";
        }
        SpannableString spannableString = SpannableString.valueOf(content);
        return getClickSpan(spannableString, flag, color, callback);
    }

    public static SpannableString getClickSpan(SpannableString spannableString, String flag, int color, ClickUrlCallback callback) {
        Pattern pattern;
        try {
            pattern = Pattern.compile(flag, Pattern.CASE_INSENSITIVE);
        } catch (Exception e) {
            String patten = Pattern.quote(flag);
            pattern = Pattern.compile(patten, Pattern.CASE_INSENSITIVE);
        }
        Matcher matcher = pattern.matcher(spannableString.toString());
        while (matcher.find()) {
            spannableString.setSpan(new UrlClick(matcher.group(), color, callback), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }

    public static boolean isUrl(String str) {
        return !TextUtils.isEmpty(str) && URLUtil.isNetworkUrl(str.trim());
    }

    public interface ClickUrlCallback {
        /**
         * 点击回调
         *
         * @param url url地址
         */
        void onClick(String url);
    }

    private static class UrlClick extends ClickableSpan {

        private int mColor;
        private String mUrl;
        private ClickUrlCallback mCallback;

        UrlClick(String url, int color, ClickUrlCallback callback) {
            mUrl = url;
            mColor = color;
            mCallback = callback;
        }

        @Override
        public void onClick(View view) {
            if (mCallback != null) {
                mCallback.onClick(mUrl);
            }
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            if (mColor == 0) {
                super.updateDrawState(ds);
            } else {
                ds.setColor(mColor);
                //                ds.setUnderlineText(true);
            }

        }
    }
}
